# coding:utf-8
import urllib;
import urllib2;
import datetime;
import MySQLdb;
from ssq import MYSQL;
import re;
from django.http import HttpResponse

"""
每天跟新
"""
def update(request):
    
    method = request.method.lower();
    
    if(method == "get"):
        getDict = request.GET;
        date = -1;
        if("date" in getDict):
            "如果date有值，则更新最近几期的数据"
            date = int(getDict["date"]);
        else:
            date = 1;    
        
        str_select = "select date from tbssq order by id desc  limit 0,1";
        
        try:
        
            conn = MySQLdb.connect(host=MYSQL["host"], user=MYSQL["user"], passwd=MYSQL["passwd"], db=MYSQL["db"]);
            
            cur = conn.cursor();
            
            cur.execute(str_select);
            rt = cur.fetchall();
            ssqdate = -1;
            if(len(rt) > 0):
                ssqdate = int(rt[0][0]);
                pass
            else:
                ssqdate = 2013001;
                pass
            
            for i in range(date):
                v = ssqdate + i;
                url = "http://caipiao.163.com/award/ssq/%s.html" % v;
                req = urllib2.Request(url);
                res = urllib2.urlopen(req);
                
                str_html = res.read();
                
                "分析页面数据，找出红球与篮球"
                
                p1 = re.compile(r'[\s\S]*?<p id="zj_area">([\S\s]*?)</p>');
                m1 = re.match(p1, str_html);
                str_p = m1.group(1);
                
                pattern = re.compile(r'[\s\S]*?<span class="red_ball">([\s\S]*?)</span>[\s\S]*?');
                
                red = re.findall(pattern, str_p);
                
                pabule = re.compile(r'[\s\S]*?<span class="blue_ball">([\s\S]*?)</span>[\s\S]*?');
                
                bule = re.findall(pabule, str_p);
                
                "根据日期查看数据库中是否存在数据如果存在数据则跟新数据，不存在则插入数据"
                str_select = "select count(*) from tbssq where date='%s'" % str(v);
                
                cur.execute(str_select);
                rt = cur.fetchall();
                
                flag = int(rt[0][0]);
                
                l = red + bule;
                l.append(str(v));
                t = tuple(l);
                
                if(flag == 0):
                    "插入"
                    str_insert = "insert into tbssq(r1,r2,r3,r4,r5,r6,b,date) values(%s,%s,%s,%s,%s,%s,%s,%s)" % t;
                    cur.execute(str_insert);
                    conn.commit();
                    
                else:
                    str_update = "update tbssq set r1=%s,r2=%s,r3=%s,r4=%s,r5=%s,r6=%s,b=%s where date=%s" % t;
                    cur.execute(str_insert);
                    conn.commit();
                    
                    pass;
            
            return HttpResponse("update ok")
                
            
        except Exception, e:
            return HttpResponse(e);
            pass
        finally:
            
            cur.close();
            conn.close();
            
            pass
        
    pass

"""
猜测随机数
"""
def rnd(request):
    
    "根据最近30期来分析"
    "首先查询出数据"
    
    try:
        
        conn = MySQLdb.connect(host=MYSQL["host"], user=MYSQL["user"], passwd=MYSQL["passwd"], db=MYSQL["db"]);
        str_select = "select r1,r2,r3,r4,r5,r6,b,date from tbssq order by date desc limit 30";
        
        cursor = conn.cursor();
            
        cursor.execute(str_select);
        rt = cursor.fetchall();
        
        "按日期来排列一个字典 按数字来排列一个字典"
        dateDict = {};
        numbDict = {};
        
        for v in rt:
            if( v[7] not in dateDict):
                dateDict[v[7]]=[];
            dateDict[v[7]].append(v);
            l = len(v);
            for i in range(l-2):
                tv = v[i];
                if(tv not in numbDict):
                    numbDict[tv]=[];
                numbDict[tv].append(v[:l]);
        str_res="";
        for key in numbDict.keys():
            
            str_res += key+":"+str(len(numbDict[key]))+"    ";
            
            pass
        
        return HttpResponse(str_res);
        
        
        pass
    except Exception,e:
        return HttpResponse(e);
        pass
    finally:
        
        cursor.close();
        conn.close();
        
        pass
    
    pass